<template>
  <van-nav-bar
    :style="{
      '--van-nav-bar-background': navBarBgColor,
      '--van-nav-bar-title-text-color': navBarTextColor,
      '--van-nav-bar-icon-color': navBarIconColor
    }"
    fixed
    safe-area-inset-top
    placeholder
    :left-arrow="showBackButton"
    @click-left="handleBackClick"
  >
    <!-- 首页显示 logo -->
    <template v-if="isHomePage" #left>
      <img
        v-if="companyStore.headimgurl"
        :src="companyStore.headimgurl"
        alt="logo"
        class="w-26 h-26 rounded-8"
        loading="lazy"
      />
    </template>

    <!-- 非首页显示标题 -->
    <template v-else #title>
      {{ routeTitle }}
    </template>

    <!-- 首页显示右侧图标 -->
    <template v-if="isHomePage" #right>
      <div class="relative cursor-pointer" @click="navigateTo('PackageList')">
        <img
          :src="`${IMG_CDN_39}/home/title_entry_pakcage.png?t=1`"
          class="w-90 h-14"
          alt="套餐入口"
          loading="lazy"
        />
        <img
          :src="`${IMG_CDN_39}/home/marketingGift/star.png`"
          class="-top-6 -right-5 w-10 h-10 title-package-star absolute"
          alt="闪烁星星"
          loading="lazy"
        />
      </div>
    </template>
  </van-nav-bar>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useCompanyStoreHook } from "@/store/modules/company";
import { useScrollStore } from "@/store/modules/scrollStore";
import { IMG_CDN_39 } from "@/constants";
const props = defineProps({
  // 导航栏类型 1-默认 2-自定义类型
  NavBarType: {
    type: Number,
    default: 1
  },
  // 标题
  title: {
    type: String,
    default: ""
  }
});
// 父组件调用emit方法，通知子组件
const emit = defineEmits(["confirm"]);

// 路由和路由管理器
const route = useRoute();
const router = useRouter();

// 公司信息存储
const companyStore = useCompanyStoreHook();

// 滚动状态存储
const scrollStore = useScrollStore();

// 滚动位置
const scrollY = ref(0);

// 定义常用颜色配置
const TRANSPARENT_BLACK = {
  bg: "transparent",
  text: "#000000",
  icon: "#000000"
};
const TRANSPARENT_WHITE = {
  bg: "transparent",
  text: "#ffffff",
  icon: "#ffffff"
};
const BLACK_BLACK = { bg: "#000000", text: "#000000", icon: "#000000" };
const BLACK_WHITE = { bg: "#000000", text: "#ffffff", icon: "#ffffff" };
const PACKAGE_LIST = { bg: "#1C1A45", text: "#ffffff", icon: "#ffffff" };
const MEMBER = { bg: "#f5f5f5", text: "#000000", icon: "#000000" };
const Generate_Detail = { bg: "#D8E3FE", text: "#000000", icon: "#000000" };
const SPREAD = {
  bg: "linear-gradient(180deg, #D5DAFF 0%, #FFFFFF 16vh)",
  text: "#000000",
  icon: "#000000"
};
const WHITE_BLACK = { bg: "#ffffff", text: "#000000", icon: "#000000" };

// 定义路由颜色配置常量（使用提取的配置）
const ROUTE_COLORS = {
  Home: BLACK_BLACK,
  TemplateList: BLACK_WHITE,
  History: TRANSPARENT_BLACK,
  AICoinRecord: TRANSPARENT_BLACK,
  MyHuman: TRANSPARENT_BLACK,
  MyHumanHistory: TRANSPARENT_BLACK,
  OrderList: TRANSPARENT_BLACK,
  OrderDetails: TRANSPARENT_BLACK,
  Spread: SPREAD,
  Setting: TRANSPARENT_BLACK,
  Member: MEMBER,
  PackageList: PACKAGE_LIST,
  TempleVideo: TRANSPARENT_WHITE,
  CreatePictureVideo: TRANSPARENT_WHITE,
  AiCopyGenerator: TRANSPARENT_WHITE,
  AiCopyGenHistory: TRANSPARENT_WHITE,
  NoTrainVideoIntro: TRANSPARENT_BLACK,
  GenerateDetail: Generate_Detail,
  Default: WHITE_BLACK
} as const;

// 计算属性
const routeName = computed(() => route.name as string);
// 修改后的routeTitle计算属性：对TempleVideo路由特殊处理
const routeTitle = computed(() => {
  // 如果是子定义类型返回对应的标题
  if (props.NavBarType === 2) {
    return props.title;
  }
  // 如果路由参数中有name，则优先使用参数中的name
  if (route.params.name) {
    return route.params.name as string;
  }
  // 其他情况使用路由meta中的title
  return route.meta.title || "默认标题";
});
const isHomePage = computed(() => routeName.value === "Home");

// 是否为底部导航栏页面
const showBackButton = computed(() => {
  const tabbarPages = ["Home", "History", "Member"];
  return !routeName.value || !tabbarPages.includes(routeName.value);
});

// 导航栏背景色
const navBarBgColor = computed(() => {
  if (routeName.value === "PackageList") {
    return scrollY.value > 46 ? ROUTE_COLORS.PackageList.bg : "transparent";
  }
  if (routeName.value === "NoTrainVideoIntro") {
    return scrollY.value > 46 ? "#ffffff" : ROUTE_COLORS.NoTrainVideoIntro.bg;
  }

  return ROUTE_COLORS[routeName.value]?.bg || ROUTE_COLORS.Default.bg;
});

// 导航栏文字颜色
const navBarTextColor = computed(() => {
  return ROUTE_COLORS[routeName.value]?.text || ROUTE_COLORS.Default.text;
});

// 导航栏图标颜色
const navBarIconColor = computed(() => {
  return ROUTE_COLORS[routeName.value]?.icon || ROUTE_COLORS.Default.icon;
});

// 获取公司信息
const fetchCompanyInfo = async () => {
  try {
    // 如果已经获取过，直接返回
    if (companyStore.hasFetched) return;

    // 调用store的方法获取公司信息
    await companyStore.fetchCompanyInfo();
  } catch (error) {
    console.error("获取公司信息失败:", error);
  }
};

// 导航到指定页面
const navigateTo = (routeName: string) => {
  router.push({ name: routeName });
};

// 处理返回点击
const handleBackClick = () => {
  if (props.NavBarType === 2) {
    emit("confirm");
  } else {
    if (routeName.value === "Home") return;
    router.back();
  }
};

// 滚动节流处理
let lastScrollTime = 0;
const handleScroll = () => {
  const now = Date.now();
  if (now - lastScrollTime < 50) return;

  lastScrollTime = now;
  scrollY.value = window.scrollY;
  scrollStore.setScrollY(scrollY.value);
};

// 监听路由元信息变化
watch(
  () => route.meta.title,
  newTitle => {
    // 强制触发重新计算
    route.meta.title = newTitle;
  }
);

// 生命周期钩子
onMounted(() => {
  fetchCompanyInfo();
  window.addEventListener("scroll", handleScroll, { passive: true });
});

onUnmounted(() => {
  window.removeEventListener("scroll", handleScroll);
});
</script>

<style scoped>
@keyframes star-blink {
  0% {
    opacity: 0.2;
    transform: scale(0.8);
  }
  50% {
    opacity: 1;
    transform: scale(1.1);
  }
  100% {
    opacity: 0.8;
    transform: scale(1);
  }
}

.title-package-star {
  animation: star-blink 0.8s ease-out infinite;
  will-change: opacity, transform;
}

.cursor-pointer {
  cursor: pointer;
}
</style>
